{"componentChunkName":"component---src-templates-post-jsx","path":"/[CS]Heap/","result":{"data":{"site":{"siteMetadata":{"title":"SUbbb"}},"markdownRemark":{"id":"4c2e96a9-4c71-57e3-b8e4-220b2cdf3002","excerpt":"🧷 힙(Heap) 우선순위 큐를 위해 만들어진 자료구조이다. 삽입과 삭제 모두 으로 해결할 수 있다. 완전 이진 트리의 일종이다. 여러 값 중, 최댓값과 최솟값을 빠르게 찾아내도록 만들어진 자료구조 반 정렬 상태 (무조건 정렬되어 있을 필요가 없다.) 힙 트리는 중복된 값 허용 (이진 탐색 트리는 중복값을 허용하지 않음) 우선순위 큐?\n: 우선순위의 개념…","html":"<h2>🧷 힙(Heap)</h2>\n<p>우선순위 큐를 위해 만들어진 자료구조이다.</p>\n<ul>\n<li>삽입과 삭제 모두 <span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>O</mi><mo stretchy=\"false\">(</mo><mi>l</mi><mi>o</mi><mi>g</mi><mi>N</mi><mo stretchy=\"false\">)</mo></mrow><annotation encoding=\"application/x-tex\">O(logN)</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:1em;vertical-align:-0.25em;\"></span><span class=\"mord mathnormal\" style=\"margin-right:0.02778em;\">O</span><span class=\"mopen\">(</span><span class=\"mord mathnormal\" style=\"margin-right:0.01968em;\">l</span><span class=\"mord mathnormal\">o</span><span class=\"mord mathnormal\" style=\"margin-right:0.03588em;\">g</span><span class=\"mord mathnormal\" style=\"margin-right:0.10903em;\">N</span><span class=\"mclose\">)</span></span></span></span>으로 해결할 수 있다.</li>\n<li>\n<p>완전 이진 트리의 일종이다.</p>\n<ul>\n<li>여러 값 중, 최댓값과 최솟값을 빠르게 찾아내도록 만들어진 자료구조</li>\n</ul>\n</li>\n<li>반 정렬 상태 (무조건 정렬되어 있을 필요가 없다.)</li>\n<li>힙 트리는 중복된 값 허용 (이진 탐색 트리는 중복값을 허용하지 않음)</li>\n</ul>\n<blockquote>\n<p><strong>우선순위 큐?</strong>\n: 우선순위의 개념을 큐에 도입한 자료구조로, 데이터들이 우선순위를 가지고 있고 이에 따라 우선순위가 높은 데이터가 먼저 나가게 되는 구조이다.</p>\n<ul>\n<li>우선순위 큐는 배열, 연결리스트, 힙으로 구현할 수 있는데, 그 중 힙이 가장 효율적이다.</li>\n</ul>\n</blockquote>\n<blockquote>\n<p><strong>완전 이진 트리?</strong>\n: 노드를 삽입할 때, 왼쪽부터 차례대로 삽입하는 트리이다.</p>\n</blockquote>\n<h3>🪚 종류</h3>\n<p><strong>최대 힙(Max Heap)</strong></p>\n<ul>\n<li>부모 노드의 키 값이 자식 노드의 키 값보다 크거나 같은 완전 이진 트리</li>\n</ul>\n<p><strong>최소 힙(Min Heap)</strong></p>\n<ul>\n<li>부모 노드의 키 값이 자식 노드의 키 값보다 작거나 같은 완전 이진 트리</li>\n</ul>\n<h3>🪚 구현</h3>\n<p>힙을 저장하는 표준적 자료구조는 <code class=\"language-text\">배열</code> 이다.</p>\n<ul>\n<li>구현을 쉽게 하기 위해 배열의 첫 번째 인덱스인 0은 사용되지 않는다.</li>\n<li>특정 위치의 노드 번호는 새로운 노드가 추가되어도 변하지 않는다.</li>\n</ul>\n<p><strong>부모 노드와 자식 노드의 관계</strong></p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">왼쪽 자식 index = (부모 index) * 2\n오른쪽 자식 index = (부모 index) * 2 + 1\n부모 index = (자식 index) / 2</code>\n        </deckgo-highlight-code>\n<p><strong>삽입</strong></p>\n<ol>\n<li>힙에 새로운 요소가 들어오면, 일단 새로운 노드를 힙의 마지막 노드에 삽입</li>\n<li>새로운 노드를 부모 노드들과 교환</li>\n</ol>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">// 최대 힙의 삽입 구현\n\nvoid insertMaxHeap(int x) {\n  // 힙 크기를 증가시키고, 마지막 노드에 삽입\n  maxHeap[++heapSize] = x;\n\n  for (int i = heapSize; i &gt; 1; i/=2) {\n    // 마지막 노드가 자신의 부모 노드보다 크면 swap\n    if (maxHeap[i/2] &lt; maxHeap[i]) swap(i/2, i);\n    else break;\n  }\n}</code>\n        </deckgo-highlight-code>\n<p><strong>삭제</strong></p>\n<ol>\n<li>최대 힙에서 최댓값은 루트 노드이므로 루트 노드가 삭제됨</li>\n<li>삭제된 루트 노드에는 힙의 마지막 노드를 가져옴</li>\n<li>힙을 재구성(<code class=\"language-text\">heapify</code>)</li>\n</ol>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">// 최대 힙 삭제 구현\n\nint deleteMaxHeap() {\n  if (heapSize == 0) return 0;\n\n  // 루트 노드의 값을 저장하고, 마지막 노드 값을 루트로 이동한 후 힙 크기를 줄여 마지막 노드를 0으로 초기화\n  int item = maxHeap[1];\n  maxHeap[1] = maxHeap[heapSize];\n  maxHeap[heapSize--] = 0;\n\n  for (int i = 1; i*2 &lt;= heapSize;) {\n    // 마지막 노드가 왼쪽 노드와 오른쪽 노드보다 크면 최대 힙이므로 종료\n    if (maxHeap[i] &gt; maxHeap[i*2] &amp;&amp; maxHeap[i] &gt; maxHeap[i*2+1]) break;\n    // 자식 노드가 더 큰 경우, 교환한 후, i를 변경\n    else if (maxHeap[i*2] &gt; maxHeap[i*2+1]) {\n      swap(i, i*2);\n      i *= 2;\n    } else {\n      swap(i, i*2+1);\n      i = i*2+1;\n    }\n  }\n\n  return item;\n}</code>\n        </deckgo-highlight-code>\n<hr>\n<h2>📕 참고</h2>\n<ul>\n<li><a href=\"https://gyoogle.dev/blog/computer-science/data-structure/Heap.html\">Tech Interview for developer</a></li>\n</ul>","frontmatter":{"title":"📂 Heap","date":"May 21, 2022","update":"May 21, 2022","tags":["개발상식","Java","힙"],"series":"📂 Computer Science"},"fields":{"slug":"/[CS]Heap/","readingTime":{"minutes":3.995}}},"seriesList":{"edges":[{"node":{"id":"3fe44622-13ba-589a-bbe8-01581ea7eb50","fields":{"slug":"/[CS]배열/"},"frontmatter":{"title":"📂 배열 (Array)"}}},{"node":{"id":"5b487c3d-e474-5a07-a26c-fc8c7d7cab22","fields":{"slug":"/[CS]연결리스트/"},"frontmatter":{"title":"📂 연결 리스트 (Linked List)"}}},{"node":{"id":"57149a6b-c730-5ce4-a3c5-9cea44979c8c","fields":{"slug":"/[CS]Array&ArrayList&LinkedList/"},"frontmatter":{"title":"📂 Array vs. ArrayList vs. LinkedList"}}},{"node":{"id":"28dac540-50bf-57df-afd9-9561888e8889","fields":{"slug":"/[CS]Stack&Queue/"},"frontmatter":{"title":"📂 Stack & Queue"}}},{"node":{"id":"4c2e96a9-4c71-57e3-b8e4-220b2cdf3002","fields":{"slug":"/[CS]Heap/"},"frontmatter":{"title":"📂 Heap"}}},{"node":{"id":"44f6bf8c-3235-5ff7-9d5f-f7c816218acb","fields":{"slug":"/[CS]Trie/"},"frontmatter":{"title":"📂 Trie(트라이)"}}},{"node":{"id":"81b508c5-2689-54e4-b36f-2e8bd07e2297","fields":{"slug":"/[CS]Tree/"},"frontmatter":{"title":"📂 Tree(트리)"}}},{"node":{"id":"2efb6036-05bf-594e-b9b5-03e399be6f78","fields":{"slug":"/[CS]이진탐색트리/"},"frontmatter":{"title":"📂 이진탐색트리(Binary Search Tree)"}}},{"node":{"id":"d1ac08af-f215-5176-9cd8-df1760f4ff7e","fields":{"slug":"/[CS]BTree&B+Tree/"},"frontmatter":{"title":"📂 B Tree & B+ Tree"}}}]},"previous":{"fields":{"slug":"/[면접]Overloading&Overriding/"},"frontmatter":{"title":"💬 Overloading vs. Overriding"}},"next":{"fields":{"slug":"/[Programmers]17679/"},"frontmatter":{"title":"👩‍💻 17679. 프렌즈4블록"}}},"pageContext":{"id":"4c2e96a9-4c71-57e3-b8e4-220b2cdf3002","series":"📂 Computer Science","previousPostId":"ff639c50-31d5-5f1f-8a8c-33a4f0a5912a","nextPostId":"bd175d9e-2352-5f9f-9611-2af5a1ae82f4"}},"staticQueryHashes":[]}